//! 增强的服务器trait接口设计
//! 
//! 基于SOLID原则重新设计的trait接口体系，实现高内聚低耦合的架构

use async_trait::async_trait;
use std::io;
use std::any::Any;
use std::sync::Arc;
use crate::storage::RedisServerMode;

// =============================================================================
// 配置管理抽象层
// =============================================================================

/// 服务器配置管理接口 - 单一职责原则
#[async_trait]
pub trait ServerConfig: Send + Sync + std::fmt::Debug {
    /// 获取服务器模式
    fn mode(&self) -> RedisServerMode;
    
    /// 获取绑定地址
    fn bind_address(&self) -> &str;
    
    /// 验证配置
    fn validate(&self) -> Result<(), String>;
    
    /// 获取额外配置
    fn extra_config(&self) -> Option<&dyn Any>;
    
    /// 克隆配置
    fn clone_config(&self) -> Box<dyn ServerConfig>;
}

// =============================================================================
// 服务生命周期管理抽象层 
// =============================================================================

/// 服务生命周期管理接口 - 单一职责原则
#[async_trait]
pub trait ServiceLifecycle: Send + Sync {
    /// 服务类型名称
    fn service_name(&self) -> &'static str;
    
    /// 启动服务
    async fn start(&mut self) -> io::Result<()>;
    
    /// 停止服务  
    async fn stop(&mut self) -> io::Result<()>;
    
    /// 重启服务
    async fn restart(&mut self) -> io::Result<()> {
        self.stop().await?;
        self.start().await
    }
    
    /// 获取服务状态
    fn is_running(&self) -> bool;
    
    /// 优雅关闭
    async fn graceful_shutdown(&mut self, timeout_secs: u64) -> io::Result<()>;
}

/// 服务健康检查接口
#[async_trait]
pub trait HealthCheck: Send + Sync {
    /// 健康检查
    async fn health_check(&self) -> Result<HealthStatus, String>;
    
    /// 获取诊断信息
    async fn diagnostics(&self) -> Vec<DiagnosticInfo>;
}

/// 健康状态
#[derive(Debug, Clone, PartialEq)]
pub enum HealthStatus {
    Healthy,
    Degraded(String),
    Unhealthy(String),
}

/// 诊断信息
#[derive(Debug, Clone)]
pub struct DiagnosticInfo {
    pub component: String,
    pub status: String,
    pub details: Option<String>,
}

// =============================================================================
// 服务组件工厂抽象层 - 工厂模式
// =============================================================================

/// 服务组件工厂接口 - 开闭原则
#[async_trait]
pub trait ServiceComponentFactory: Send + Sync {
    /// 创建Redis服务组件
    async fn create_redis_service(&self, config: &dyn ServerConfig) -> io::Result<Box<dyn ServiceLifecycle>>;
    
    /// 创建集群服务组件  
    async fn create_cluster_service(&self, config: &dyn ServerConfig) -> io::Result<Option<Box<dyn ServiceLifecycle>>>;
    
    /// 创建监控服务组件
    async fn create_monitoring_service(&self, config: &dyn ServerConfig) -> io::Result<Option<Box<dyn ServiceLifecycle>>>;
    
    /// 支持的服务器模式
    fn supported_modes(&self) -> Vec<RedisServerMode>;
}

// =============================================================================
// 事件系统抽象层 - 观察者模式
// =============================================================================

/// 服务器事件
#[derive(Debug, Clone)]
pub enum ServerEvent {
    Starting { mode: RedisServerMode },
    Started { mode: RedisServerMode, bind_addr: String },
    Stopping { mode: RedisServerMode },
    Stopped { mode: RedisServerMode },
    Error { message: String, recoverable: bool },
    ConfigChanged { old_mode: RedisServerMode, new_mode: RedisServerMode },
}

/// 事件监听器接口
#[async_trait]
pub trait ServerEventListener: Send + Sync + std::fmt::Debug {
    /// 处理服务器事件
    async fn on_event(&mut self, event: ServerEvent) -> Result<(), String>;
    
    /// 监听器名称
    fn listener_name(&self) -> &str;
}

/// 事件发布器接口
#[async_trait]
pub trait ServerEventPublisher: Send + Sync {
    /// 注册事件监听器
    async fn subscribe(&mut self, listener: Arc<dyn ServerEventListener>) -> Result<(), String>;
    
    /// 取消注册事件监听器
    async fn unsubscribe(&mut self, listener_name: &str) -> Result<(), String>;
    
    /// 发布事件
    async fn publish(&self, event: ServerEvent) -> Result<(), String>;
}

// =============================================================================
// 增强的服务器模式接口 - 组合多个职责
// =============================================================================

/// 增强的服务器模式接口 - 依赖倒置原则
#[async_trait]
pub trait EnhancedServerMode: Send + Sync {
    /// 获取配置
    fn config(&self) -> &dyn ServerConfig;
    
    /// 获取组件工厂
    fn component_factory(&self) -> &dyn ServiceComponentFactory;
    
    /// 获取事件发布器
    fn event_publisher(&self) -> &dyn ServerEventPublisher;
    
    /// 启动服务器 - 模板方法模式
    async fn start(&mut self) -> io::Result<()> {
        // 发布启动事件
        let mode = self.config().mode();
        self.event_publisher().publish(ServerEvent::Starting { mode }).await
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
        
        // 执行具体启动逻辑
        self.do_start().await?;
        
        // 发布启动完成事件
        let mode = self.config().mode(); // 重新获取，避免移动问题
        let bind_addr = self.config().bind_address().to_string();
        self.event_publisher().publish(ServerEvent::Started { mode, bind_addr }).await
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
        
        Ok(())
    }
    
    /// 停止服务器 - 模板方法模式
    async fn stop(&mut self) -> io::Result<()> {
        let mode = self.config().mode();
        
        // 发布停止事件
        self.event_publisher().publish(ServerEvent::Stopping { mode }).await
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
        
        // 执行具体停止逻辑
        self.do_stop().await?;
        
        // 发布停止完成事件
        let mode = self.config().mode(); // 重新获取，避免移动问题
        self.event_publisher().publish(ServerEvent::Stopped { mode }).await
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
        
        Ok(())
    }
    
    /// 具体的启动实现 - 子类实现
    async fn do_start(&mut self) -> io::Result<()>;
    
    /// 具体的停止实现 - 子类实现
    async fn do_stop(&mut self) -> io::Result<()>;
    
    /// 获取服务器状态
    fn is_running(&self) -> bool;
    
    /// 获取服务器模式
    fn mode(&self) -> RedisServerMode {
        self.config().mode()
    }
}

// =============================================================================
// 具体配置实现
// =============================================================================

/// Standalone配置
#[derive(Debug, Clone)]
pub struct StandaloneConfig {
    pub bind_address: String,
}

#[async_trait]
impl ServerConfig for StandaloneConfig {
    fn mode(&self) -> RedisServerMode {
        RedisServerMode::Standalone
    }
    
    fn bind_address(&self) -> &str {
        &self.bind_address
    }
    
    fn validate(&self) -> Result<(), String> {
        if self.bind_address.is_empty() {
            return Err("绑定地址不能为空".to_string());
        }
        Ok(())
    }
    
    fn extra_config(&self) -> Option<&dyn Any> {
        None
    }
    
    fn clone_config(&self) -> Box<dyn ServerConfig> {
        Box::new(self.clone())
    }
}

/// Cluster配置  
#[derive(Debug, Clone)]
pub struct ClusterConfig {
    pub bind_address: String,
    pub cluster_config: crate::cluster::ClusterConfig,
}

#[async_trait]
impl ServerConfig for ClusterConfig {
    fn mode(&self) -> RedisServerMode {
        RedisServerMode::Cluster
    }
    
    fn bind_address(&self) -> &str {
        &self.bind_address
    }
    
    fn validate(&self) -> Result<(), String> {
        if self.bind_address.is_empty() {
            return Err("绑定地址不能为空".to_string());
        }
        self.cluster_config.validate()
    }
    
    fn extra_config(&self) -> Option<&dyn Any> {
        Some(&self.cluster_config)
    }
    
    fn clone_config(&self) -> Box<dyn ServerConfig> {
        Box::new(self.clone())
    }
}